package com.hunan.api.catv.service.biz.tencent_cloud.sms;

import cn.hutool.core.lang.UUID;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.hunan.api.catv.common.CacheKey;
import com.hunan.api.catv.common.Constants;
import com.hunan.api.catv.common.ConstantsMsg;
import com.hunan.api.catv.entity.ServiceResult;
import com.hunan.api.catv.entity.enums.SmsTypeEnum;
import com.hunan.api.catv.mq.MqConstants;
import com.hunan.api.catv.service.ResultService;
import com.hunan.api.catv.service.biz.cache.CacheBiz;
import com.hunan.api.catv.service.biz.cps.CpsBiz;
import com.hunan.api.catv.service.biz.mq.MqBiz;
import com.hunan.api.catv.service.impl.tencent_cloud.sms.SmsService;
import com.hunan.api.catv.utils.GsonUtils;
import com.hunan.api.catv.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.text.MessageFormat;

@Service
public class SmsBiz extends ResultService {

    @Autowired
    SmsService smsService;

    @Autowired
    CacheBiz cacheBiz;

    @Autowired
    MqBiz mqBiz;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    CpsBiz cpsBiz;

    public ServiceResult send(String phone, Integer smsType) {
        boolean checkResult = checkCount(phone);
        if (!checkResult) {
            return buildFail(ConstantsMsg.sms_send_often);
        }
//		if(SmsTypeEnum.CPS.getCode().equals(smsType)) {
//			ServiceResult cpsResult = cpsBiz.getMobile(phone);
//			if(!cpsResult.getStatus()) {
//				return cpsResult;
//			}
//			phone = cpsResult.getData().toString();
//    	}
        JsonObject msg = new JsonObject();
        msg.addProperty("smsType", smsType);
        msg.addProperty("phone", phone);
        String confirmId = UUID.fastUUID().toString(true);
        log.info("[SMSSend smsType:{} phone:{} confirmId:{}]", smsType, phone,confirmId);
        mqBiz.pushAndConfirm(MqConstants.sms_exchange, MqConstants.sms_routingkey, GsonUtils.toJson(msg),confirmId);
        return buildOK(true, "发送成功");
    }

    public ServiceResult checkSmsCode(Integer smsType, String phone, String sms) {
        if (ObjectUtils.isEmpty(phone) || ObjectUtils.isEmpty(sms)) {
            return buildFail(false, ConstantsMsg.sms_param_empty);
        }
        String codeKey = MessageFormat.format(CacheKey.sms_code, phone, smsType);
        Object codeObject = redisUtils.get(codeKey);
        if (ObjectUtils.isEmpty(codeObject) ) {
            return buildFail(false, ConstantsMsg.sms_code_expire);
        }
        if (!sms.equals(codeObject.toString())) {
            return buildFail(false, ConstantsMsg.sms_code_error_msg);
        }
        redisUtils.del(codeKey);
        return buildOK(true, "");
    }

    public ServiceResult sendSms(String phone, String msg, Integer smsType) {
        JsonObject smsConf = GsonUtils.fromJson(cacheBiz.getSystemDict(Constants.tencent_cloud_sms_conf), JsonObject.class);
        if (!ObjectUtils.isEmpty(smsConf)) {
            String secretId = smsConf.get("secretId").getAsString();
            String secretKey = smsConf.get("secretKey").getAsString();
            String endPoint = smsConf.get("endPoint").getAsString();
            String region = smsConf.get("region").getAsString();
            String areaCode = smsConf.get("areaCode").getAsString();
            String templateId = smsConf.get(SmsTypeEnum.getResult(smsType)).getAsString();
            String sign = smsConf.get("sign").getAsString();
            String appId = smsConf.get("appId").getAsString();
            JsonObject params = new JsonObject();
            JsonArray phoneNumberSet = new JsonArray();
            JsonArray templateParamSet = new JsonArray();
            phoneNumberSet.add(areaCode + phone);
            params.add("PhoneNumberSet", phoneNumberSet);
            params.addProperty("TemplateID", templateId);
            params.addProperty("Sign", sign);
            templateParamSet.add(msg);
            params.add("TemplateParamSet", templateParamSet);
            params.addProperty("SmsSdkAppid", appId);
            String response = smsService.sendSms(secretId, secretKey, endPoint, region, params.toString());
            if (!ObjectUtils.isEmpty(response)) {
                JsonObject resp = GsonUtils.fromJson(response, JsonObject.class);
                JsonArray sendStatusSet = resp.getAsJsonArray("SendStatusSet");
                JsonObject json = sendStatusSet.get(0).getAsJsonObject();
                String code = json.get("Code").getAsString();
                String message = json.get("Message").getAsString();
                if ("Ok".equals(code)) {
                    String codeKey = MessageFormat.format(CacheKey.sms_code, phone, smsType);
                    redisUtils.set(codeKey, msg, 300);
                    return buildOK(code, message);
                }
                return buildFail(code, message);
            }
        }
        return buildFail(false, ConstantsMsg.sms_getConf_fail);
    }

    public ServiceResult sendSms(String phone, String templateId, String... msg) {
        JsonObject smsConf = GsonUtils.fromJson(cacheBiz.getSystemDict(Constants.tencent_cloud_sms_conf), JsonObject.class);
        if (!ObjectUtils.isEmpty(smsConf)) {
            String secretId = smsConf.get("secretId").getAsString();
            String secretKey = smsConf.get("secretKey").getAsString();
            String endPoint = smsConf.get("endPoint").getAsString();
            String region = smsConf.get("region").getAsString();
            String areaCode = smsConf.get("areaCode").getAsString();
            String sign = smsConf.get("sign").getAsString();
            String appId = smsConf.get("appId").getAsString();
            JsonObject params = new JsonObject();
            JsonArray phoneNumberSet = new JsonArray();
            JsonArray templateParamSet = new JsonArray();
            phoneNumberSet.add(areaCode + phone);
            params.add("PhoneNumberSet", phoneNumberSet);
            params.addProperty("TemplateID", templateId);
            params.addProperty("Sign", sign);
            for (String placeholder : msg) {
                templateParamSet.add(placeholder);
            }
            params.add("TemplateParamSet", templateParamSet);
            params.addProperty("SmsSdkAppid", appId);
            String response = smsService.sendSms(secretId, secretKey, endPoint, region, params.toString());
            if (!ObjectUtils.isEmpty(response)) {
                JsonObject resp = GsonUtils.fromJson(response, JsonObject.class);
                JsonArray sendStatusSet = resp.getAsJsonArray("SendStatusSet");
                JsonObject json = sendStatusSet.get(0).getAsJsonObject();
                String code = json.get("Code").getAsString();
                String message = json.get("Message").getAsString();
                if ("Ok".equals(code)) {
//					String codeKey = MessageFormat.format(CacheKey.sms_code,phone);
//					redisUtils.set(codeKey, msg, 300);
                    return buildOK(code, message);
                }
                return buildFail(code, message);
            }
        }
        return buildFail(false, ConstantsMsg.sms_getConf_fail);
    }

    public boolean checkCount(String phone) {
        String key = MessageFormat.format(CacheKey.sms_phone_count, phone);
        Long loginCount = redisUtils.incr(key, 1);
        redisUtils.expire(key, 600);
        log.info("[SendSms-Check-Incr: {} {}]", key, loginCount);
        if (loginCount.intValue() > 15) {
            return false;
        }
        return true;
    }


}
